<template>
  <div ref="map" class="comp"></div>
</template>

<script setup>
import getProvinceMapInfo from "../../public/static/map.js";
import axios from "axios";
import { inject, ref, onMounted, onBeforeUnmount, watch } from "vue";
import { useStore } from "vuex";
let store = useStore();
const echarts = inject("echarts");
const api = inject("api");

// 初始化图标容器ref的值
let map = ref(null);

// 初始化echarts实例对象
let echartsInstance = null;
// 初始化数据业务
let allData = [];
watch(
  () => store.state.themeName,
  () => {
    echartsInstance.dispose();
    initEcharts();
    enitEcharts();
    asisEcharts();
  }
);
async function initEcharts() {
  let { data } = await axios.get("http://localhost:8080/static/map/china.json");
  echarts.registerMap("china", data);
  echartsInstance = echarts.init(map.value, store.state.themeName);
  let initOptions = {
    title: {
      text: "各地区农作物覆盖面积",
      top: "3%",
      left: "3%",
    },
  };

  echartsInstance.setOption(initOptions);
  echartsInstance.on("click", async (info) => {
    console.log(info);
    let { name, path } = getProvinceMapInfo(info.name);
    let { data } = await axios.get("http://localhost:8080" + path);
    echarts.registerMap(name, data);
    echartsInstance.setOption({
      series: [
        {
          map: name,
          zoom: 0.9,
          center: undefined,
        },
      ],
    });
  });
  getData();
}
async function getData() {
  let {
    data: { content },
  } = await api("CropCoverage");
  allData = content;
  enitEcharts();
}
function enitEcharts() {
  let enitOptions = {
    series: [
      {
        type: "map",
        map: "china",
        data: allData,
        roam: true,
        zoom: 1.1,
        top: "20%",
        center: undefined,
      },
    ],
    visualMap: {
      calculable: true, //显示拖拽手柄
      text: ["High", "Low"], //两端文本
      inRange: {
        color: ["orange", "orangered"],
      },
      left: "3%",
      bottom: "3%",
    },
  };
  echartsInstance.setOption(enitOptions);
  asisEcharts();
}
// 手动适配样式
function asisEcharts() {
  let width = map.value.offsetWidth;
  let scale = (width / 100) * 3.6;
  let initOptions = {
    title: {
      textStyle: {
        fontSize: scale,
      },
    },
  };
  echartsInstance.setOption(initOptions);
  echartsInstance.resize();
}
function reset() {
  echartsInstance.setOption({
    series: [
      {
        map: "china",
        zoom: 1.1,
        center: undefined, //自动获取地图的视觉中心
      },
    ],
  });
}

onMounted(() => {
  initEcharts(), window.addEventListener("resize", asisEcharts);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", asisEcharts);
});
defineExpose({
  asisEcharts,
});
</script>

<style scoped></style>
